package com.gt.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取用户ip
 */
public class GetIpUtil {
    private static Logger logger = Logger.getLogger(GetIpUtil.class);
    /**
     * 获取ip
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
//        Enumeration names = request.getHeaderNames();
//        while(names.hasMoreElements()){
//            String name = (String) names.nextElement();
//            logger.info(name+"-----"+request.getHeader(name));
//        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 解析ip
     * @param ip
     * @return
     * @throws Exception
     */
    public static JSONObject ipInfo(String ip) throws Exception {
        HttpHelper http = new HttpHelper();
        Map params = new HashMap();
        params.put("ip",ip);
        String res = http.postData("http://ip.taobao.com/service/getIpInfo.php", params, "UTF-8", 10);
        logger.info(res);
        JSONObject json = JSONObject.parseObject(res);
        return json;
//        return new String[]{JSONObject.parseObject(json.getString("data")).getString("country"),
//                JSONObject.parseObject(json.getString("data")).getString("city"),
//                JSONObject.parseObject(json.getString("data")).getString("isp")};
    }

    public static void main(String[] args) throws Exception {
        GetIpUtil.ipInfo("219.155.101.173");
    }
}
